package weekthree;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SerializeAndDeserializeBinaryTree_297 {
    private List<String> seq = null;
    private int curr = 0;

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        seq = new ArrayList<>();
        travelsal(root);
        return String.join(" ", seq);
    }

    private void travelsal(TreeNode root) {
        if (root == null) {
            seq.add("null");
            return;
        }
        seq.add(String.valueOf(root.val));
        travelsal(root.left);
        travelsal(root.right);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        seq = Arrays.asList(data.split(" "));
        curr = 0;
        return deser();
    }


    private TreeNode deser() {
        if (seq.get(curr).equals("null")) {
            curr++;
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(seq.get(curr)));
        curr++;
        root.left = deser();
        root.right = deser();
        return root;
    }



//      Definition for a binary tree node.
private class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

}
